package me.yxy.mobanddd.components;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.DateTimePath;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.StringPath;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * QueryDSL Predicate玩法辅助类
 */
public class PredicateTool {

    private static final Logger LOG = LoggerFactory.getLogger(PredicateTool.class);

    public static void notNullAnd(BooleanBuilder builder, Long value, NumberPath<Long> column) {
        if(ObjectUtils.isEmpty(value)){
            return;
        }
        builder.and(column.eq(value));
    }

    public static void notNullAnd(BooleanBuilder builder, Integer value, NumberPath<Integer> column) {
        if(ObjectUtils.isEmpty(value)){
            return;
        }
        builder.and(column.eq(value));
    }

    public static void notNullAnd(BooleanBuilder builder, String value, StringPath column) {
        if(ObjectUtils.isEmpty(value)){
            return;
        }
        builder.and(column.eq(value));
    }

    /**
     * 时间区间，只有两者都不为空时，才触发，如果需要起止的默认值，请业务代码自行处理
     * @param builder
     * @param timeStartStr
     * @param timeEndStr
     * @param createdTime
     */
    public static void notNullBetween(BooleanBuilder builder, String timeStartStr, String timeEndStr, DateTimePath<Date> createdTime) {

        if(StringUtils.isEmpty(timeStartStr) || StringUtils.isEmpty(timeEndStr)){
            return;
        }

        //TODO 可以考虑用正则表达式智能识别两个time参数的格式
        try{
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
            DateTime startTime  = formatter.parseDateTime(timeStartStr);
            DateTime endTime  = formatter.parseDateTime(timeEndStr);
            builder.and(createdTime.between(startTime.toDate(),endTime.toDate()));
        }catch (Exception e){
            LOG.error("时间 {},{} 格式解析错误",timeStartStr,timeEndStr);
        }

    }
}
